<template>
    <div class="container">
        <div class="table-breadcrumb">
            <el-breadcrumb separator-class="el-icon-arrow-right">
                <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
                <el-breadcrumb-item>店铺资料管理</el-breadcrumb-item>
                <el-breadcrumb-item>店铺装修</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div style="margin: 10px 0;padding: 20px;background-color: #fff;">
            <section class="decoration-edit">
                <section class="l" style="overflow-y: auto;">
                    <ul @dragstart="dragStart" @dragend="dragEnd">
                        <li v-for="(val, key, index) in typeList" v-if="!val.isHidden" draggable :data-type="key" :key="index + 1">
                            <!-- <span :class="val.icon"></span> -->
                            <!-- <img :class="val.icon" :src="val.icon" style="height: 40px;width: 40px;margin-bottom: 4px;"> -->
                            <span :class="val.icon" :style="{background:'url('+ val.icon +')','background-repeat': 'no-repeat','background-size': '100% 100%',height: '40px',width: '40px',}"></span>
                            <p>{{val.name}}</p>
                        </li>
                    </ul>
                </section>
                <section class="c">
                    <!-- header 不可拖拽 opacity: info.Opacity,-->
                    <div class="top-nav" @click="selectType(0)" :style="{ backgroundColor: info.NavColor,'z-index':99 }">
                        <img src="@/assets/images/topNavBlack.png">
                        <span class="tit" :style="{color: info.FontColor}">{{ info.title }}</span>
                    </div>
                    <!--  -->
                    <div class="view-content" @drop="drog" @dragover="dragOver" :style="{ backgroundColor: info.backgroundColor,'padding-top': info.isFlex == null ||info.isFlex == null ||info.isFlex == false? '74px':'0' }">
                        <Draggable v-model="view" draggable=".item">
                            <template v-for="(item, index) in view">
                                <div v-if="index > 0" :data-index="index" :key="index" class="item" @click="selectType(index)">
                                    <!-- waiting -->
                                    <template v-if="item.status && item.status == 2">
                                        <div class="wait"> {{ item.type }} </div>
                                    </template>
                                    <template v-else>
                                        <component :is="typeList[item.type]['com']" :data="item" :className="className[item.tabType]"></component>
                                    </template>
                                    <i @click="deleteItem($event, index)" class="el-icon-error"></i>
                                </div>
                            </template>
                        </Draggable>
                    </div>
                </section>
                <section class="r">
                    <EditForm :data="props" v-if="isRight"></EditForm>
                </section>
                <div class="submit-btn">
                    <el-button @click="submit">保存模板</el-button>
                    <!-- <div style="margin-top: 10px;">
                        <el-button>保存模板</el-button>
                    </div> -->
                </div>
            </section>
        </div>
        <modal title="保存模版" v-model="visible" :centered="true" :maskClosable="false" @ok="handleOk" @cancel="handleCancel">
            <div>
                <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
                    <el-form-item label="添加到:" prop="title">
                        <el-input type="text" placeholder="请输入模版名称" clearable v-model="ruleForm.title"></el-input>
                    </el-form-item>
                    <el-form-item label="快捷回复:" prop="remark">
                        <el-input type="textarea" :rows="3" placeholder="请输入模版备注" clearable v-model="ruleForm.remark"></el-input>
                    </el-form-item>

                </el-form>
            </div>
        </modal>
    </div>
</template>
<script>
    import Vue from 'vue';
    import { ACCESS_TOKEN, USER_DATA } from '@/store/mutation-types';
    import { mapGetters, mapState, mapActions } from 'vuex';
    import modal from 'ant-design-vue/lib/modal';
    import 'ant-design-vue/lib/modal/style/css'; // 或者 ant-design-vue/lib/button/style/css 加载 css 文件
    import Draggable from 'vuedraggable'
    // import { imageUpload } from '@/api/commodity'
    import EditForm from '../common/Edit/index.vue'
    import Product from '../common/View/Product'
    import Images from '../common/View/Images'
    import Banner from '../common/View/Banner'
    import Search from '../common/View/Search'
    import Notice from '../common/View/Notice'
    import Shop from '../common/View/Shop'
    // import ClassGoods from '@Decoration/View/ClassGoods'
    // NewsGoods
    import { templateAdd, templateView, templateEdit } from '@/api/api.js'
    import { InfoConfig, SearchConfig, BannerConfig, ImagesConfig, ProductConfig, TabsConfig, GridConfig, ShopConfig, ClassGoodsConfig, NoticeConfig } from '../common/defaultConfig.js'
    export default {
        name: 'Decoration',
        components: {
            modal,
            EditForm,
            Draggable,
            Product,
            Images,
            Banner,
            Search,
            Notice,
            Shop,
            // ClassGoods
        },
        data() {
            return {
                typeList: {
                    banner: {
                        name: '轮播图',
                        icon: 'https://manager.ryz1620.com/static/DIY/Banner.png',
                        com: Banner,
                        isHidden:false,
                    },
                    images: {
                        name: '图片',
                        icon: 'https://manager.ryz1620.com/static/DIY/Images.png',
                        com: Images,
                        isHidden:false,
                        
                    },
                    product: {
                        name: '商品',
                        icon: 'https://manager.ryz1620.com/static/DIY/Goods.png',
                        com: Product,
                        isHidden:false,
                    },
                    Search: {
                        name: '搜索框',
                        icon: 'https://manager.ryz1620.com/static/DIY/Search.png',
                        com: Search,
                        isHidden:true,
                    },
                    Shop: {
                        name: '店铺信息',
                        icon: 'https://manager.ryz1620.com/static/DIY/Shop.png',
                        com: Shop,
                        isHidden:true,
                    },
                    Notice: {
                        name: '公告',
                        icon: 'https://manager.ryz1620.com/static/DIY/notice.png',
                        com: Notice,
                        isHidden:false,
                        isHidden:true,
                    },
                    // ClassGoods: {
                    //     name: '分类',
                    //     icon: 'el-icon-notebook-2',
                    //     com: ClassGoods
                    // },
                },
                view: [InfoConfig],
                title: '页面标题',
                type: '',
                index: null, // 当前组件的索引
                isPush: false, // 是否已添加组件
                props: {}, // 传值
                isRight: false,
                className: {
                    1: 'one',
                    2: 'two',
                    3: 'three'
                },
                ruleForm: {
                    title: '',
                    remark: '',
                },
                rules: {
                    title: [
                        { required: true, message: '请输入模板名称', trigger: 'blur' }
                    ],
                },
                visible: false,
                itemId:null
            }
        },
        computed: {
            info() {
                return InfoConfig
            }
        },
        mounted(){
            const that = this;
            that.itemId = that.$route.query.id;
            if(that.itemId){
                that.templateView()
            }
        },
        methods: {
            // model窗点击确定
            handleOk() {
                var that = this
                that.$refs['ruleForm'].validate((valid) => {
                    if (valid) {
                        that.AddTemplate()
                    } else {
                        return false;
                    }
                });
            },

            // 获取详情
            async templateView(){
                const that = this;
                let params = {
                    id:that.itemId
                }
                let res = await templateView(params)
                if(res.data.code == 1){
                    let data = res.data.data;
                    console.log(JSON.parse(data.content));
                    let contentData = JSON.parse(data.content);
                    that.view = contentData
                    that.ruleForm.title = data.title
                    that.ruleForm.remark = data.remark
                }
            },

            // model窗点击取消
            handleCancel() {
                var that = this
                that.ruleForm.title = ''
                that.ruleForm.remark = ''
                that.$refs['ruleForm'].resetFields();
            },
            AddTemplate() {
                var that = this
                // JSON 转换会丢失 formData
                const user = Vue.ls.get(USER_DATA);
                const form = JSON.stringify(this.view)
                var params = {
                    partner_id: user.identityId,
                    partner_type: 'medical',
                    title: that.ruleForm.title,
                    content: form,
                    remark: that.ruleForm.remark,
                }
                if(that.itemId){
                    // console.log(params);
                    params.id = that.itemId;
                    templateEdit(params).then(res => {
                        if (res.data.code === 1) {
                            this.visible = false
                            this.$message.success('编辑成功！')
                        } else {
                            that.$message.error(res.data.msg)
                        }
                    }).catch(err => {
                        that.$message.error(err.msg ? err.msg : err.toString())
                    })
                }else{
                    // console.log(params);
                    templateAdd(params).then(res => {
                        if (res.data.code === 1) {
                            this.visible = false
                            this.$message.success('添加成功！')
                        } else {
                            that.$message.error(res.data.msg)
                        }
                    }).catch(err => {
                        that.$message.error(err.msg ? err.msg : err.toString())
                    })
                }
            },
            submit() {
                // JSON 转换会丢失 formData
                const form = JSON.parse(JSON.stringify(this.view))
                // console.log(form);
                if (form.length == 1) {
                    this.$message.error('请添加模块！')
                    return
                }
                for (let i of form) {
                    // console.log(i);
                    if (i.type == 'banner' || i.type == 'images') {
                        // console.log(i);
                        if (i.data && i.data.length == 0) {
                            // console.log(i.data);
                            this.$message.error('请完善' + i.name + '信息！')
                            return
                        }
                    }
                }
                this.visible = true
                console.log(form) // 提交的数据，根据接口形式修改
                return
            },
            // 切换视图组件
            selectType(index) {
                this.isRight = false
                this.props = this.view[index]
                this.$nextTick(() => this.isRight = true)
            },
            deleteItem(e, index) {
                e.preventDefault()
                e.stopPropagation()
                this.view.splice(index, 1)
                this.isRight = false
                this.props = {}
            },
            // 拖拽类型
            dragStart(e) {
                console.log('dragStart',e);
                this.type = e.target.dataset.type
                
            },
            // 结束拖拽
            dragEnd(e) {
                console.log('dragEnd',e);
                this.$delete(this.view[this.index], 'status')
                this.isPush = false
                this.type = null
            },
            // 已放置到指定位置
            drog(e) {
                if (!this.type) { // 内容拖拽
                    return
                }
                e.preventDefault()
                e.stopPropagation()
                this.dragEnd()
            },
            // 移动中
            dragOver(e) {
                if (!this.type) { // 内容拖拽
                    return
                }
                e.preventDefault()
                e.stopPropagation()

                let className = e.target.className
                let name = className !== 'view-content' ? 'item' : 'view-content'

                let defaultData = {
                    // type: this.type, // 组件类型
                    // status: 2, // 默认状态
                    // data: [], // 数据
                    // options: {} // 选项操作
                }
                switch (this.type) {
                    case 'Search':
                        defaultData = JSON.parse(JSON.stringify(SearchConfig))
                        break;
                    case 'banner':
                        defaultData = JSON.parse(JSON.stringify(BannerConfig))
                        break;
                    case 'images':
                        defaultData = JSON.parse(JSON.stringify(ImagesConfig))
                        break;
                    case 'product':
                        defaultData = JSON.parse(JSON.stringify(ProductConfig))
                        break;
                        // case 'Tabs':
                        //     defaultData = JSON.parse(JSON.stringify(TabsConfig))
                        //     break;
                    case 'ClassGoods':
                        defaultData = JSON.parse(JSON.stringify(ClassGoodsConfig))
                        break;
                    case 'Shop':
                        defaultData = JSON.parse(JSON.stringify(ShopConfig))
                        break;
                    case 'Notice':
                        defaultData = JSON.parse(JSON.stringify(NoticeConfig))
                        break;

                }
                if (name == 'view-content') {
                    if (!this.isPush) {
                        this.index = this.view.length
                        this.isPush = true
                        this.view.push(defaultData)
                    }
                } else if (name == 'item') {

                    let target = e.target
                    let [y, h, curIndex] = [e.offsetY, target.offsetHeight, target.dataset.index]
                    let direction = y < (h / 2)

                    if (!this.isPush) {
                        // Push to Top or Bottom
                        if (direction) {
                            if (curIndex == 0) {
                                this.view.unshift(defaultData)
                            } else {
                                this.view.splice(curIndex, 0, defaultData)
                            }
                        } else {
                            curIndex = +curIndex + 1
                            this.view.splice(curIndex, 0, defaultData)
                        }
                    } else {
                        // Moving
                        if (direction) {
                            var i = curIndex == 0 ? 0 : curIndex - 1
                            var result = this.view[i]['status'] == 2
                        } else {
                            var i = +curIndex + 1
                            var result = this.view.length > i && this.view[i]['status'] == 2
                        }

                        if (result) return

                        const temp = this.view.splice(this.index, 1)
                        this.view.splice(curIndex, 0, temp[0])
                    }
                    this.index = curIndex
                    this.isPush = true
                }
            }
        }
    };
</script>
<style lang="less" scoped>
    .decoration-edit {
        display: flex;
        align-items: flex-start;
        justify-content: space-between;
        padding: 10px 10px;
        background: #f7f8f9;
        height: calc(100vh - 180px);
        position: relative;

        .l,
        .r {
            width: 340px;
            height: 100%;
            overflow-y:scroll;
            padding: 15px 0;
            background: #fff;
            box-shadow: 0 2px 6px #ccc;
        }

        .l {
            ul {
                margin: 0;
                padding: 0;
                display: flex;
                align-items: center;
                /* justify-content: space-between; */
                flex-wrap: wrap;

                li {
                    width: 25%;
                    height: 80px;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    flex-direction: column;
                    cursor: default;
                    list-style: none;
                    font-size: 14px;
                    color: #666;
                    float: left;
                    /* margin: 0 10px; */
                    border-radius: 6px;
                    transition: all .3s;
                    cursor: pointer;

                    &:hover {
                        background: #efefef;
                    }

                    span {
                        display: block;
                        font-size: 40px;
                        margin-bottom: 8px;
                        color: #999;
                    }

                    p {
                        display: block;
                        margin: 0;
                        font-size: 12px;
                    }
                }
            }

            ul:after {
                content: '';
                width: 25%;
            }
        }

        .c {
            width: auto;
            max-width: 400px;
            position: relative;
            .top-nav {
                position: absolute;
                top: 0;
                background: #fff;
                /* z-index: 999; */
                transition: all .3s;

                & * {
                    pointer-events: none;
                }

                &:hover {
                    transform: scale(0.95);
                    border-radius: 10px;
                    overflow: hidden;
                    box-shadow: 0 0 10px #afafaf;
                }

                .tit {
                    position: absolute;
                    left: 50%;
                    bottom: 16px;
                    transform: translateX(-50%);
                }

                img {
                    max-width: 100%;
                    image-rendering: -moz-crisp-edges;
                    image-rendering: -o-crisp-edges;
                    image-rendering: -webkit-optimize-contrast;
                    image-rendering: crisp-edges;
                    -ms-interpolation-mode: nearest-neighbor;
                }
            }

            .view-content {
                width: 400px;
                height: 740px;
                background: #f5f5f5;
                overflow-y: auto;
                overflow-x: hidden;
                padding-top: 74px;
                box-shadow: 0 2px 6px #ccc;

                &::-webkit-scrollbar {
                    width: 6px;
                }

                &::-webkit-scrollbar-thumb {
                    background: #dbdbdb;
                }

                &::-webkit-scrollbar-track {
                    background: #f6f6f6;
                }

                .item {
                    transition: all .3s;
                    /* background: #fff; */

                    &:hover {
                        transform: scale(0.95);
                        border-radius: 10px;
                        box-shadow: 0 0 10px #afafaf;

                        .el-icon-error {
                            display: block;
                        }
                    }

                    div {
                        pointer-events: none;
                    }

                    .wait {
                        background: #deedff;
                        height: 35px;
                        text-align: center;
                        line-height: 35px;
                        font-size: 12px;
                        color: #666;
                    }

                    .el-icon-error {
                        position: absolute;
                        right: -10px;
                        top: -6px;
                        color: red;
                        font-size: 25px;
                        cursor: pointer;
                        display: none;
                        z-index: 9999;
                    }
                }
            }
        }

        .submit-btn {
            position: absolute;
            top: 20px;
            right: 26%;
            transform: translateX(-50%);
            z-index: 1000;
        }
    }
</style>